<template>
  <!-- @closed="editing=false" 关闭屉式菜单  重置编辑状态为不编辑 -->
  <van-action-sheet
    :value="value"
    @closed="editing = false"
    @input="$emit('input', $event)"
    title="编辑频道"
  >
    <!---------------------------- 我的频道 ------------------------------->
    <div class="channel">
      <!-- 操作区 -->
      <div class="tit">
        我的频道：
        <span class="tip">点击可进入频道</span>
        <van-button
          v-if="!editing"
          @click="editing = true"
          size="mini"
          type="info"
          plain
          >编辑</van-button
        >
        <van-button
          v-else
          @click="editing = false"
          size="mini"
          type="danger"
          plain
          >完成</van-button
        >
      </div>
      <!-- 内容区 -->
      <van-grid class="van-hairline--left">
        <van-grid-item v-for="(item, index) in MyChannelList" :key="item.id">
          <span
            @click="enterChannel(index)"
            class="f12"
            :class="{ red: channelIndex === index }"
            >{{ item.name }}</span
          >
          <!-- 删除按钮 -->
          <van-icon
            @click="delChannel(item.id, index)"
            v-show="editing && index !== 0"
            class="btn"
            name="cross"
          ></van-icon>
        </van-grid-item>
      </van-grid>
    </div>

    <!----------------------------- 可选频道 ------------------------------->
    <div class="channel">
      <div class="tit">可选频道：</div>
      <van-grid class="van-hairline--left">
        <van-grid-item v-for="item in optionalChannels" :key="item.id">
          <span class="f12">{{ item.name }}</span>
          <!-- 点击添加频道 -->
          <van-icon
            @click="addChannel(item)"
            class="btn"
            name="plus"
          ></van-icon>
        </van-grid-item>
      </van-grid>
    </div>
  </van-action-sheet>
</template>
<script>
// 导入各种调用接口的api方法
import { getAllChannelApi, delChannelApi, addChannelApi } from '@/api/channel.js'
export default {
  // ======================= props =======================
  props: {
    // 打开/关闭的状态
    value: {
      type: Boolean,
      default: false
    },
    MyChannelList: {
      type: Array,
      default: () => []
    },
    channelIndex: {
      type: Number,
      default: 0
    }
  },
  // ======================== data =======================
  data () {
    return {
      // 编辑状态
      editing: false,
      // 所有频道列表
      AllChannelList: []
    }
  },
  // ======================== created =====================
  created () {
    this.getAllChannel()
  },
  // ======================== methods =====================
  methods: {
    // -------------- 获取所有频道 -------------
    async getAllChannel () {
      const { data } = await getAllChannelApi()
      // console.log(data.channels)
      this.AllChannelList = data.channels
    },

    // --------------- 切换频道 ---------------
    enterChannel (index) {
      // console.log(index)
      // 1. 进入
      // this.$emit('enter-channel', index)
      this.$emit('update:activeIndex', index)
      // 2.关闭弹层
      this.$emit('input', false)
    },

    // --------------- 删除频道 ----------------
    async delChannel (id, index) {
      try {
        // 1.调用接口删除（数据库删除）2.成功提示 3.前端删除(数组删除)
        await delChannelApi(id)
        this.$toast.success('删除成功')

        // 如果删除选中频道之前的频道，选中出问题 ==>  解决：当前选中频道索引值减一=》向前进一步
        if (index < this.channelIndex) {
          this.$emit('update:activeIndex', this.channelIndex - 1)
        }
        this.MyChannelList.splice(index, 1)
      } catch (error) {
        this.$toast.success('删除失败')
      }
    },

    // --------------- 添加频道 ----------------
    async addChannel (channel) {
      /**
       * 后端需要的数据：[{id:频道ID, seq:索引值}]=》我的频道数据+当前新增频道
       * 1. 处理我的频道myChannel数据格式
       * 2. 把新增的加到处理完的我的频道数据中，保持一样的格式
       * 3. 删除推荐数据
       */
      const data = this.MyChannelList.map((item, index) => {
        return { id: item.id, seq: index }
      })
      data.push({ id: channel.id, seq: data.length })
      data.shift()
      // console.log('添加api需要传参的数据: ', data)
      // 调用接口,更新添加频道数据,前端也要添加
      try {
        await addChannelApi(data)
        this.$toast.success('新增成功')
        this.MyChannelList.push(channel)
      } catch (error) {
        this.$toast.fail('新增失败')
      }
    }
  },
  // ------------- 计算不喜欢的频道列表数据 --------------
  computed: {
    optionalChannels () {
      return this.AllChannelList.filter(all => {
        // return this.MyChannelList.findIndex(my => my.id === all.id) === -1
        // my.id === all.id 如果有就为true, filter需要的是有就返回false不要这条数据
        return !this.MyChannelList.some(my => my.id === all.id)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.van-popup--bottom {
  &.van-popup--round {
    border-radius: 0;
  }
}
.van-action-sheet {
  max-height: 100%;
  height: 100%;
  .van-action-sheet__header {
    background: #3296fa;
    color: #fff;
    .van-icon-close,
    .van-action-sheet__close {
      color: #fff;
    }
  }
}
.channel {
  padding: 10px;
  .tit {
    line-height: 3;
    text-align: left;
    .tip {
      font-size: 10px;
      color: #999;
    }
  }
  .van-button {
    float: right;
    margin-top: 7px;
  }
  .btn {
    position: absolute;
    bottom: 0;
    right: 0;
    background: #ddd;
    font-size: 12px;
    color: #fff;
  }
  .f12 {
    font-size: 12px;
    color: #555;
  }
  .red {
    color: red;
  }
}
</style>
